package study.transaction.jdbc.service;

import cn.hutool.db.DbUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import study.transaction.jdbc.dao.accountbase.AccountBaseDao;
import study.transaction.jdbc.dao.accountbase.AccountBaseEO;
import study.transaction.jdbc.dao.userbase.UserBaseDao;
import study.transaction.jdbc.dao.userbase.UserBaseEO;

import java.sql.Connection;

@Slf4j
public class UserService {

    @SneakyThrows
    public void addUser(boolean throwEx) {
        //连接
        Connection conn = DbUtil.newSession().getConnection();
        //====== 提交模式 ======
        conn.setAutoCommit(false);
        //
        try {
            //
            UserBaseDao ubDao = new UserBaseDao(conn);
            UserBaseEO ubEO = UserBaseEO.builder()
                    .ubLoginName("test").build();
            ubDao.insert(ubEO);
            log.info("连接id {}", ubDao.getConnId());

            //
            if (throwEx) throw new RuntimeException("我是一个业务异常");

            //
            AccountBaseDao abDao = new AccountBaseDao(conn);
            AccountBaseEO abEO = AccountBaseEO.builder()
                    .abUbId(ubEO.getUbId()).build();
            abDao.insert(abEO);
            log.info("连接id {}", abDao.getConnId());

            //====== 事务提交 ======
            conn.commit();
        } catch (Exception ex) {
            //====== 事务回滚 ======
            conn.rollback();
        } finally {
            DbUtil.close(conn);
        }
    }
}
